<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <el-button type="success" size="default">初始化菜单</el-button>
        <el-button type="primary" size="default" @click="toAddMenu"
          >新增菜单</el-button
        >
      </div>

      <vxe-table
        resizable
        border
        ref="xTree"
        :data="tableData"
        :tree-config="{
          children: 'children',
          iconOpen: 'vxe-icon--arrow-bottom',
          iconClose: 'vxe-icon--arrow-right',
        }"
        @toggle-tree-expand="toggleExpandChangeEvent"
      >
        <vxe-column field="title" title="菜单名称" tree-node></vxe-column>
        <vxe-column field="icon" title="图标">
          <template #default="{ row }">
            <i :class="row.icon"></i>
          </template>
        </vxe-column>
        <vxe-column field="level" title="等级"></vxe-column>
        <vxe-column field="sort" title="排序"></vxe-column>
        <vxe-column field="permissionValue" title="权限标识"></vxe-column>
        <vxe-column field="path" title="路由"></vxe-column>
        <vxe-column field="component" title="组件路径"></vxe-column>
        <vxe-column field="status" title="是否可用"></vxe-column>
        <vxe-column field="createTime" title="创建时间"></vxe-column>
      </vxe-table>
    </el-card>

    <!-- 编辑菜单 -->
    <el-dialog
      title="编辑菜单"
      @close="close"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <div class="div">
        <span class="span">菜单类型</span>
        <el-radio-group v-model="radio" @change="radioChange">
          <el-radio :label="1">顶级目录</el-radio>
          <el-radio :label="2">菜单</el-radio>
          <el-radio :label="3">按钮</el-radio>
        </el-radio-group>
      </div>
      <!-- radio为1和2的表单 -->
      <el-form
        :model="formList"
        label-width="120px"
        label-fontSize="20px"
        :inline="false"
        size="normal"
        ref="formList"
        :rules="rules"
        v-if="radio == 1 || radio == 2"
      >
        <el-form-item
          v-if="radio == 2"
          class="label"
          label="上级菜单"
          prop="name"
          style="width: 320px"
        >
          <el-cascader
            :options="selectArr"
            show-all-levels
            :props="{ checkStrictly: true, expandTrigger: 'hover' }"
            @change="selectProp"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item class="label" label="路由名称" prop="name">
          <el-input
            v-model="formList.name"
            placeholder="前端路由name,唯一"
          ></el-input>
        </el-form-item>
        <el-form-item class="label" label="路径" prop="path">
          <el-input
            v-model="formList.path"
            placeholder="前端路由path,忽略父节点路径"
          ></el-input>
        </el-form-item>
        <el-form-item class="label" label="组件路径" prop="component">
          <el-input
            v-model="formList.component"
            placeholder="前端路由组件路径,比如@/views/foo/foo.vue"
          ></el-input>
        </el-form-item>
        <el-form-item class="label" label="重定向">
          <el-input
            v-model="formList.redirect"
            placeholder="redirect属性"
          ></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item class="label" label="排序">
              <el-input-number v-model="formList.sort"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="radio == 2">
            <el-form-item class="label" label="层级">
              <el-input-number v-model="formList.level"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item class="label" label="是否隐藏">
              <el-radio-group v-model="formList.hidden">
                <el-radio :label="false">否</el-radio>
                <el-radio :label="true">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item class="label" label="是否展开">
              <el-radio-group v-model="formList.alwaysShow">
                <el-radio :label="false">否</el-radio>
                <el-radio :label="true">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col
            :span="3"
            :offset="0"
            style="font-size: 20px; text-align: right"
            >meta属性</el-col
          >
          <el-col :span="20" :offset="0" v-if="metaShow">
            <el-input
              class="ipt"
              v-model="meta[0].title"
              placeholder=""
              size="normal"
              clearable
            ></el-input>
            <el-input
              class="ipt"
              v-model="meta[0].icon"
              placeholder=""
              size="normal"
              clearable
            ></el-input>
            <span class="span-click" @click="addMeta">+</span>
            <span class="span-click" v-if="radio == 2" @click="del">-</span>
          </el-col>
          <el-col :span="20" :offset="3" v-if="metaShow">
            <el-input
              class="ipt"
              v-model="meta[1].title"
              placeholder=""
              size="normal"
              clearable
            ></el-input>
            <el-input
              class="ipt"
              v-model="meta[1].icon"
              placeholder=""
              size="normal"
              clearable
            ></el-input>
            <span class="span-click" @click="addMeta">+</span>
            <span class="span-click" v-if="radio == 2" @click="del">-</span>
          </el-col>
          <el-col :span="20" :offset="3" v-for="item in iptArr" :key="item.id">
            <el-input
              class="ipt"
              v-model="item.title"
              placeholder=""
              size="normal"
              clearable
            ></el-input>
            <el-input
              class="ipt"
              v-model="item.icon"
              placeholder=""
              size="normal"
              clearable
            ></el-input>
            <span class="span-click" @click="addMeta">+</span>
            <span class="span-click" @click="reduceMeta(item.id)">-</span>
          </el-col>
        </el-row>
      </el-form>
      <!-- radio为3的表单 -->
      <el-form
        :model="btnForm"
        label-width="120px"
        :inline="false"
        size="normal"
        ref="btnForm"
        :rules="rulesBtn"
      >
        <el-form-item
          class="label"
          prop="title"
          label="所在页面"
          style="width: 320px"
        >
          <el-cascader
            :options="selectArr"
            show-all-levels
            :props="{ checkStrictly: true, expandTrigger: 'hover' }"
            @change="selectProp"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="按钮名称" prop="title">
          <el-input
            v-model="btnForm.title"
            placeholder="按钮名称,比如: 新增"
          ></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item class="label" label="排序">
              <el-input-number v-model="btnForm.sort"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="label" label="层级">
              <el-input-number v-model="btnForm.level"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="权限标识" prop="permissionValue">
          <el-input
            type="textarea"
            v-model="btnForm.permissionValue"
            placeholder="按钮权限标识,比如: productList.list"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="enter">确 定</el-button>
      </span>
    </el-dialog>

    <buttomBanner></buttomBanner>
  </div>
</template>

<script>
import {
  findAllPermissions,
  save,
} from "@/api/permissions/resources/resources.js";
import buttomBanner from "@/components/buttomBanner";
import { v4 as uuidv4 } from "uuid";
export default {
  name: "Resources",
  data() {
    return {
      btnForm: {
        level: 0,
        sort: 0,
        type: 2,
      },
      btnSaveForm: {},
      metaShow: true,
      formSave: {},
      selectArr: [],
      iptArr: [],
      radio: 1,
      meta: [
        {
          title: "title",
          icon: "未命名",
        },
        {
          title: "icon",
          icon: "el-icon-menu",
        },
      ],
      formList: {
        alwaysShow: true,
        hidden: false,
        level: 1,
        sort: 0,
        pid: "",
        type: 1,
      },
      tableData: [],
      dialogVisible: false,
      rules: {
        name: [{ required: true, message: "请输入路由", trigger: "blur" }],
        path: [{ required: true, message: "请输入路径", trigger: "blur" }],
        component: [
          { required: true, message: "请输入组件路径", trigger: "blur" },
        ],
      },
      rulesBtn: {
        title: [{ required: true, message: "请选择/输入", trigger: "blur" }],
        permissionValue: [
          { required: true, message: "请选择/输入", trigger: "blur" },
        ],
      },
    };
  },
  components: {
    buttomBanner,
  },
  methods: {
    close() {
      if (this.radio == 3) {
        // 清除按钮表单校验
        this.$refs.btnForm.clearValidate();
      } else {
        // 清除1和2的表单校验，因为他们是一个表单，3是另一个表单
        this.$refs.formList.clearValidate();
      }
    },
    // radio改变
    radioChange(v) {
      // 将保存的初始值赋值分别给两个表单,初始值在页面加载时储存
      this.formList = this.formSave;
      this.btnForm = this.btnSaveForm;
      // 清空表单校验同上述
      if (v == 3) {
        this.$refs.btnForm.clearValidate();
      } else {
        this.$refs.formList.clearValidate();
      }
    },
    // 弹窗菜单页面删除meta
    del() {
      this.metaShow = false;
      this.meta = [];
    },
    // 级联选择器
    selectProp(v) {
      this.formList.pid = v.slice(-1).join(",");
      this.btnForm.pid = v.slice(-1).join(",");
    },
    // 确定
    enter() {
      // 判断弹窗处于那个页面1-顶级目录，2-菜单，3-按钮
      if (this.radio == 1 || this.radio == 2) {
        this.formList.type = 1;
      } else if (this.radio == 3) {
        this.formList.type = 2;
      }
      // 将参数转为合法值
      this.iptArr.map((el) => {
        return delete el.id;
      });
      var arr = [...this.iptArr, ...this.meta];
      var obj = {};
      if (arr.length == 0) {
        this.formList.meta = "{}";
        delete this.formList.icon;
        delete this.formList.title;
      } else {
        arr.forEach((el) => {
          obj[el.title] = el.icon;
        });
        this.formList.meta = JSON.stringify(obj);
        this.formList.icon = obj.icon;
        this.formList.title = obj.title;
      }

      // 表单验证,按钮3和1,2不是用的一个表单,所以分开写
      if (this.radio == 3) {
        this.$refs.btnForm.validate((valid) => {
          if (valid) {
            save(this.btnForm).then((res) => {
              console.log(res);
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else {
        this.$refs.formList.validate((valid) => {
          if (valid) {
            save(this.formList).then((res) => {
              console.log(res);
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
      // this.$refs.formList.validate((valid) => {
      //   if (valid) {
      //     save(this.formList).then((res) => {
      //       console.log(res);
      //     });
      //   } else {
      //     console.log("error submit!!");
      //     return false;
      //   }
      // });

      // this.formSave = this.$options.data()
      // console.log(obj);
      // console.log(this.formList);
      // console.log(this.iptArr);
      // console.log(this.radio);
    },
    // 删除当行meta
    reduceMeta(id) {
      var index = this.iptArr.findIndex((el) => el.id == id);
      this.iptArr.splice(index, 1);
    },
    // 新增meta
    addMeta() {
      this.iptArr.push({ title: "", icon: "", id: uuidv4() });
    },
    // 新增菜单
    toAddMenu() {
      this.dialogVisible = true;
      this.formList = this.formSave;
    },
    toggleExpandChangeEvent() {},
    // 初始化
    init() {
      findAllPermissions().then((res) => {
        if (res.success) {
          this.tableData = res.data.menus;
          // 将获得的值转化为符合树形级联选择器的类型
          this.selectArr = fun(res.data.menus);
          console.log(this.selectArr);
          // 树形级联选择器数据，递归求得
          function fun(array) {
            var arr = [];
            array.forEach((el, index) => {
              var obj = {};
              // 有子children就递归
              if (el.children.length !== 0) {
                obj = {
                  value: el.id,
                  label: el.title,
                };
                arr.push(obj);
                // 重点，在对象里增加children数组
                arr[index].children = fun(el.children);
              } else {
                obj = { value: el.id, label: el.title, disabled: true };
                arr.push(obj);
              }
            });
            return arr;
          }
        }
      });
    },
  },
  created() {
    this.init();
    this.formSave = this.$options.data().formList;
    this.btnSaveForm = this.$options.data().btnForm;
  },
};
</script>

<style lang="scss" scope>
.el-form-item__label {
  font-size: 20px !important;
  font-weight: normal;
}
.div {
  margin-bottom: 15px;
  .span {
    display: inline-block;
    text-align: right;
    font-size: 20px;
    width: 120px;
    padding-right: 12px;
    vertical-align: middle;
  }
}
.el-input {
  margin-bottom: 10px;
}
.ipt {
  width: 322px;
  margin-right: 20px;
}
.span-click {
  width: 25px;
  display: inline-block;
  height: 25px;
  font-size: 20px;
}
.el-cascader {
  width: 300px;
}
</style>